package com.jyxd.web.jobhandler;

import com.alibaba.fastjson.JSON;
import com.jyxd.web.dao.patient.PatientDao;
import com.jyxd.web.data.basic.MedOrderBackupsExec;
import com.jyxd.web.data.basic.MedOrderExec;
import com.jyxd.web.data.dto.HttpResult;
import com.jyxd.web.data.hisview.HisYb;
import com.jyxd.web.data.patient.Patient;
import com.jyxd.web.service.assessment.basic.MedOrderBackupsExecService;
import com.jyxd.web.service.assessment.basic.MedOrderExecService;
import com.jyxd.web.service.assessment.basic.MonitorLifeDataService;
import com.jyxd.web.service.assessment.basic.VitalSignMergeService;
import com.jyxd.web.service.hisview.HisViewService;
import com.jyxd.web.service.hisyb.HisybService;
import com.jyxd.web.service.patient.PatientService;
import com.jyxd.web.util.DateUtil;
import com.jyxd.web.util.SpringUtil;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.transaction.Transactional;
import java.util.*;

import static com.jyxd.web.util.DateUtil.*;
import static com.jyxd.web.util.UUIDUtil.getUUID;

@Component
public class IcuJobHandler {
    private static final Logger logger = LoggerFactory.getLogger(IcuJobHandler.class);

    /**
     * 同步医保数据
     *
     * @throws Exception
     */
    @XxlJob("syncHisYB")
    @Transactional
    public void syncHisYBJobHandle() throws Exception {
        HisybService hisybService = SpringUtil.getBean(HisybService.class);
        //查询本地的医保数据
        List<HisYb> list = hisybService.queryYBDataAll();
        List<HisYb> newList = new ArrayList<HisYb>();
        if (list != null && list.size() > 0) {
            //如果HIS数据库有数据不管，没有数据新增
            for (int i = 0; i < list.size(); i++) {
                //通过id查询his库判断有没有数据，没有放到新的list中
                HisYb hisYb = hisybService.queryData(list.get(i).getDataid());

                if (hisYb == null) {
                    newList.add(list.get(i));
                }
            }
            if (!newList.isEmpty()) {
                //插入数据库
                for (int i = 0; i < newList.size(); i++) {
                    //通过id查询his库判断有没有数据，没有放到新的list中
                    hisybService.insert(list.get(i));
                }
            }
        }
    }

    /**
     * 定时删除监护仪数据
     *
     * @throws Exception
     */
    @XxlJob("deleteMonitorLifeDataJob")
    public void deleteMonitorLifeDataJob() throws Exception {
        MonitorLifeDataService monitorLifeDataService = SpringUtil.getBean(MonitorLifeDataService.class);
        Map<String, Object> map = new HashMap<>();
        map.put("startTime", "2021-01-01 00:00:00");
        //改为删除两天之前的数据，由于数据太多导致前台页面直接卡死
        Date laterHoursDate = getLaterHoursDate(new Date(), -48L);
        String endTime = yyyyMMddHHmmssSdfToString(laterHoursDate);
        map.put("endTime", endTime);
        monitorLifeDataService.deleteData(map);
    }

    /**
     * 定时同步HIS患者基本表
     *
     * @throws Exception
     */
    @XxlJob("syncHISQualityControlJob")
    public void syncHISQualityControlJob() throws Exception {
        PatientDao patientDao = SpringUtil.getBean(PatientDao.class);
        HisViewService hisViewService = SpringUtil.getBean(HisViewService.class);
        //查询本地的患者数据
        List<Patient> patientList = patientDao.getPatientAllList();
        //Patient patient = patientDao.queryData("5dabfa722bbf4d2d9ce06434494d9972");
        int sum = 0;
        int count = 0;
        if (patientList != null && patientList.size() > 0) {
            sum = patientList.size();
            //如果HIS数据库有数据更新，没有数据新增
            for (int i = 0; i < patientList.size(); i++) {
                hisViewService.handleDcIcuDatBrxxjlk(patientList.get(i));
                count = i;
            }
            // for (Patient patient : patientList) {
            //     hisViewService.handleDcIcuDatBrxxjlk(patient);
            //    count=patientList[i]
            // }
        }
    }

    @XxlJob("syncNursingVitalSignsJob")
    public void syncNursingVitalSignsJob() throws Exception {
        VitalSignMergeService vitalSignMergeService = SpringUtil.getBean(VitalSignMergeService.class);
        PatientService patientService = SpringUtil.getBean(PatientService.class);
        String param = XxlJobHelper.getJobParam();
        List<Patient> patients = patientService.queryPatientByFlagAndBed(param);
        long start = System.currentTimeMillis();
        if (!CollectionUtils.isEmpty(patients)) {
            String time = DateUtil.yyyyMMddHHmmSdfToString(new Date());
            Map<String, String> map = new HashMap<String, String>();
            map.put("time", time);
            for (Patient patient : patients) {
                map.put("patientId", patient.getId());
                logger.info("time: " + time + "  --  patientId: " + patient.getId());
                HttpResult httpResult = vitalSignMergeService.syncVitalSignMerge(map, null);
                if (logger.isDebugEnabled()) {
                    logger.debug(JSON.toJSONString(httpResult));
                }
            }
        }
        logger.info("[定时任务->生成护理单数据]-耗时:{}", System.currentTimeMillis() - start);
    }


    @XxlJob("backupMedOrderBackupsJob")
    public void backupMedOrderBackupsJob() throws Exception {
        MedOrderExecService medOrderExecService = SpringUtil.getBean(MedOrderExecService.class);
        MedOrderBackupsExecService medOrderBackupsExecService = SpringUtil.getBean(MedOrderBackupsExecService.class);
        Date laterMonthDate = getLaterMonthDate(new Date(), -3l);
        Map<String, Object> map = new HashMap<>();
        map.put("startTime", laterMonthDate);
        List<MedOrderExec> medOrderExecList = medOrderExecService.queryByCreateTime(map);
        if (CollectionUtils.isEmpty(medOrderExecList))
            return;
        medOrderExecList.forEach(medOrderExec -> {
            MedOrderBackupsExec medOrderBackupsExec = new MedOrderBackupsExec();
            medOrderBackupsExec.setId(getUUID());
            medOrderBackupsExec.setVisitId(medOrderExec.getVisitId());
            medOrderBackupsExec.setVisitCode(medOrderExec.getVisitCode());
            medOrderBackupsExec.setPatientId(medOrderExec.getPatientId());
            medOrderBackupsExec.setOrderCode(medOrderExec.getOrderCode());
            medOrderBackupsExec.setOrderNo(medOrderExec.getOrderNo());
            medOrderBackupsExec.setOrderSubNo(medOrderExec.getOrderSubNo());
            medOrderBackupsExec.setOrderName(medOrderExec.getOrderName());
            medOrderBackupsExec.setSpecs(medOrderExec.getSpecs());
            medOrderBackupsExec.setDrugType(medOrderExec.getDrugType());
            medOrderBackupsExec.setOrderAttr(medOrderExec.getOrderAttr());
            medOrderBackupsExec.setDefaultTimePoint(medOrderExec.getDefaultTimePoint());
            medOrderBackupsExec.setExecuteDate(medOrderExec.getExecuteDate());
            medOrderBackupsExec.setExplicitTimeInterval(medOrderExec.getExplicitTimeInterval());
            medOrderBackupsExec.setDuration(medOrderExec.getDuration());
            medOrderBackupsExec.setStartTimePoint(medOrderExec.getStartTimePoint());
            medOrderBackupsExec.setCompleteTimePoint(medOrderExec.getCompleteTimePoint());
            medOrderBackupsExec.setEntryTime(medOrderExec.getEntryTime());
            medOrderBackupsExec.setDosage(medOrderExec.getDosage());
            medOrderBackupsExec.setQuantity(medOrderExec.getQuantity());
            medOrderBackupsExec.setQuantityUnits(medOrderExec.getQuantityUnits());
            medOrderBackupsExec.setDosageUnits(medOrderExec.getDosageUnits());
            medOrderBackupsExec.setAllDosage(medOrderExec.getAllDosage());
            medOrderBackupsExec.setTotalNumber(medOrderExec.getTotalNumber());
            medOrderBackupsExec.setRepeatIndicator(medOrderExec.getRepeatIndicator());
            medOrderBackupsExec.setUseMode(medOrderExec.getUseMode());
            medOrderBackupsExec.setClassType(medOrderExec.getClassType());
            medOrderBackupsExec.setFrequency(medOrderExec.getFrequency());
            medOrderBackupsExec.setFrequencyEndTime(medOrderExec.getFrequencyEndTime());
            medOrderBackupsExec.setPerformSpeed(medOrderExec.getPerformSpeed());
            medOrderBackupsExec.setSpeedUnits(medOrderExec.getSpeedUnits());
            medOrderBackupsExec.setNurseCode(medOrderExec.getNurseCode());
            medOrderBackupsExec.setOrderStatus(medOrderExec.getOrderStatus());
            medOrderBackupsExec.setRemark(medOrderExec.getRemark());
            medOrderBackupsExec.setDoctorAdvice(medOrderExec.getDoctorAdvice());
            medOrderBackupsExec.setCreateTime(medOrderExec.getCreateTime());
            medOrderBackupsExec.setUpdateTime(medOrderExec.getUpdateTime());
            medOrderBackupsExec.setIsSync(medOrderExec.getIsSync());
            medOrderBackupsExec.setOrderExecNum(medOrderExec.getOrderExecNum());
            medOrderBackupsExec.setSyncNum(medOrderExec.getSyncNum());
            medOrderBackupsExec.setRecentSyncTime(medOrderExec.getRecentSyncTime());
            medOrderBackupsExec.setIdm(medOrderExec.getIdm());
            medOrderBackupsExec.setDosageForm(medOrderExec.getDosageForm());
            medOrderBackupsExec.setCoefficient(medOrderExec.getCoefficient());
            medOrderBackupsExec.setTreatmentRoute(medOrderExec.getTreatmentRoute());
            medOrderBackupsExec.setStatus(medOrderExec.getStatus());
            medOrderBackupsExecService.insert(medOrderBackupsExec);
        });
        medOrderExecService.deleteByCreateTime(map);
    }

}
